function showStatus(message, isError = false) {
    const statusMessageElement = document.getElementById('statusMessage');
    statusMessageElement.textContent = message;
    statusMessageElement.style.color = isError ? 'red' : 'green';
}

document.addEventListener('DOMContentLoaded', () => {
    const downloadPageButton = document.getElementById('downloadCurrentPage');
    const openSettingsButton = document.getElementById('openSettings');
    const resourceList = document.getElementById('resourceList');

    downloadPageButton.addEventListener('click', () => {
        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
            const currentTab = tabs[0];
            if (currentTab) {
                chrome.runtime.sendMessage(
                    {action: 'download_current_page', url: currentTab.url},
                    response => {
                        if (chrome.runtime.lastError) {
                            showStatus('Error: ' + chrome.runtime.lastError.message, true);
                        } else if (response && response.success) {
                            showStatus('Download request sent for current page.');
                        } else {
                            showStatus('Download request failed for current page.', true);
                        }
                    }
                );
            }
        });
    });

    openSettingsButton.addEventListener('click', () => {
        chrome.tabs.create({url: chrome.runtime.getURL('popup/settings.html')});
    });

    // Request sniffed resources from background script
    chrome.runtime.sendMessage({action: 'get_sniffed_resources'}, (response) => {
        if (chrome.runtime.lastError) {
            console.error('Error getting sniffed resources:', chrome.runtime.lastError.message);
            showStatus('Error loading sniffed resources.', true);
            return;
        }

        if (response && response.resources && response.resources.length > 0) {
            const subtitleList = document.getElementById('subtitleList');
            response.resources.forEach(resource => {
                const listItem = document.createElement('li');
                const resourceLink = document.createElement('a');
                resourceLink.href = resource.url;
                resourceLink.textContent = resource.url.length > 50 ? resource.url.substring(0, 47) + '...' : resource.url;
                resourceLink.target = '_blank'; // Open in new tab

                const downloadButton = document.createElement('button');
                downloadButton.textContent = 'Download Subtitle';
                downloadButton.style.marginLeft = '10px';
                downloadButton.addEventListener('click', () => {
                    chrome.runtime.sendMessage(
                        {action: 'download_subtitle', url: resource.url},
                        response => {
                            if (chrome.runtime.lastError) {
                                showStatus('Error downloading subtitle: ' + chrome.runtime.lastError.message, true);
                            } else if (response && response.success) {
                                showStatus('Subtitle download initiated.');
                            } else {
                                showStatus('Subtitle download failed.', true);
                            }
                        }
                    );
                });

                listItem.appendChild(resourceLink);
                listItem.appendChild(downloadButton);
                subtitleList.appendChild(listItem);
            });
        } else {
            const subtitleList = document.getElementById('subtitleList');
            const listItem = document.createElement('li');
            listItem.textContent = 'No subtitles sniffed yet.';
            subtitleList.appendChild(listItem);
        }
    });

    const pasteFromClipboardButton = document.getElementById('pasteFromClipboard');
    const clipboardContentElement = document.getElementById('clipboardContent');
    const downloadClipboardUrlButton = document.getElementById('downloadClipboardUrl');

    // Remove the direct event listener for downloadSubtitleButton as it will be handled dynamically
    // const downloadSubtitleButton = document.getElementById('downloadSubtitle');
    // if (downloadSubtitleButton) {
    //   downloadSubtitleButton.addEventListener('click', () => {
    //     const subtitleUrl = 'http://example.com/subtitle.srt';
    //     chrome.runtime.sendMessage(
    //       { action: 'download_subtitle', url: subtitleUrl },
    //       response => {
    //         if (chrome.runtime.lastError) {
    //           showStatus('Error downloading subtitle: ' + chrome.runtime.lastError.message, true);
    //         } else if (response && response.success) {
    //           showStatus('Subtitle download initiated.');
    //         } else {
    //           showStatus('Subtitle download failed.', true);
    //         }
    //       }
    //     );
    //   });
    // }

    pasteFromClipboardButton.addEventListener('click', async () => {
        try {
            const text = await navigator.clipboard.readText();
            clipboardContentElement.textContent = text;

            // Basic URL validation
            const urlRegex = /^(https?:\/\/[^\s]+)$/;
            if (urlRegex.test(text)) {
                downloadClipboardUrlButton.style.display = 'inline-block';
                downloadClipboardUrlButton.onclick = () => {
                    chrome.runtime.sendMessage(
                        {action: 'download_resource', url: text},
                        response => {
                            if (chrome.runtime.lastError) {
                                showStatus('Error downloading clipboard URL: ' + chrome.runtime.lastError.message, true);
                            } else if (response && response.success) {
                                showStatus('Download request sent for clipboard URL.');
                            } else {
                                showStatus('Download request failed for clipboard URL.', true);
                            }
                        }
                    );
                };
            } else {
                downloadClipboardUrlButton.style.display = 'none';
            }
        } catch (err) {
            console.error('Failed to read clipboard contents: ', err);
            showStatus('Failed to read clipboard. Please grant clipboard permissions.', true);
        }
    });

    const dropArea = document.getElementById('dropArea');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => dropArea.classList.add('highlight'), false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => dropArea.classList.remove('highlight'), false);
    });

    dropArea.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const url = dt.getData('URL');

        if (url) {
            // Basic URL validation
            const urlRegex = /^(https?:\/\/[^\s]+)$/;
            if (urlRegex.test(url)) {
                chrome.runtime.sendMessage(
                    {action: 'download_resource', url: url},
                    response => {
                        if (chrome.runtime.lastError) {
                            showStatus('Error downloading dropped URL: ' + chrome.runtime.lastError.message, true);
                        } else if (response && response.success) {
                            showStatus('Download request sent for dropped URL.');
                        } else {
                            showStatus('Download request failed for dropped URL.', true);
                        }
                    }
                );
            } else {
                showStatus('Dropped content is not a valid URL.', true);
            }
        } else {
            showStatus('No URL found in dropped content.', true);
        }
    }
});

const downloadCustomUrlButton = document.getElementById('downloadCustomUrl');
if (downloadCustomUrlButton) {
    downloadCustomUrlButton.addEventListener('click', () => {
        const customDownloadUrlInput = document.getElementById('customDownloadUrl');
        const url = customDownloadUrlInput.value.trim();
        if (url) {
            chrome.runtime.sendMessage({action: 'download_custom_url', url: url}, response => {
                if (chrome.runtime.lastError) {
                    console.error('Error sending message:', chrome.runtime.lastError.message);
                    statusMessage.textContent = 'Error: ' + chrome.runtime.lastError.message;
                    statusMessage.style.color = 'red';
                } else if (response && response.success) {
                    statusMessage.textContent = 'Download initiated for custom URL!';
                    statusMessage.style.color = 'green';
                    customDownloadUrlInput.value = ''; // Clear input after initiating download
                } else {
                    statusMessage.textContent = response && response.message ? 'Error: ' + response.message : 'Unknown error initiating download.';
                    statusMessage.style.color = 'red';
                }
            });
        } else {
            statusMessage.textContent = 'Please enter a URL to download.';
            statusMessage.style.color = 'orange';
        }
    });
}